package com.coffee.web.controller;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.service.RedisService;
import com.coffee.admin.api.merchant.result.MerchantResult;
import com.coffee.admin.api.merchant.service.MerchantService;
import com.coffee.core.anotation.LoginCheck;
import com.coffee.core.anotation.LoginStatus;
import com.coffee.core.anotation.OperLog;
import com.coffee.core.entity.LoginUser;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.*;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.result.Result;
import com.coffee.core.util.DateUtil;
import com.coffee.core.util.IpUtils;
import com.coffee.core.util.StringUtil;
import com.coffee.order.api.inquire.service.InquireOrderService;
import com.coffee.order.api.sku.query.OrderBalanceQuery;
import com.coffee.order.api.sku.req.*;
import com.coffee.order.api.sku.result.*;
import com.coffee.order.api.sku.service.CommonPayService;
import com.coffee.order.api.sku.service.OrderBalanceService;
import com.coffee.order.api.sku.service.SkuOrderService;
import com.coffee.web.utils.WeixinAppletsUtil;
import com.coffee.web.utils.WeixinGzhAppletsUtil;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/merchant")
public class OrderController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Value("${parameter.webDomain}")
    private String webDomain;
    @Value("${TAG}")
    private String environment;

    @DubboReference
    private SkuOrderService skuOrderService;
    @DubboReference
    private OrderBalanceService orderBalanceService;
    @DubboReference
    private CommonPayService commonPayService;
    @DubboReference
    private InquireOrderService inquireOrderService;
    @DubboReference
    private MerchantService merchantService;
    @DubboReference
    private RedisService redisService;

    @OperLog(operModul = "商户-抵扣金额", operDesc = "购物车抵扣金额")
    @LoginCheck
    @RequestMapping(value = "/integralPrice", method = {RequestMethod.POST})
    public Result<CarPriceResult> skuPlaceOrder(@RequestBody SkuOrderAddReq skuOrderAddReq, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Result<CarPriceResult> result = Result.success(null);
        CarPriceResult integralPrice = skuOrderService.getIntegralPrice(skuOrderAddReq.getCityId(), merchant.getUserId(), skuOrderAddReq.getSkuShopcarId(), skuOrderAddReq.getIsUseIntegral());
        result.setData(integralPrice);
        return result;
    }

    @OperLog(operModul = "商户-抵扣金额", operDesc = "单个抵扣金额")
    @LoginCheck
    @RequestMapping(value = "/integralBySku", method = {RequestMethod.POST})
    public Result<CarPriceResult> integralBySku(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer skuId = jsonObject.getInteger("skuId");
        Integer skuSalesInformationId = jsonObject.getInteger("skuSalesInformationId");
        Integer count = jsonObject.getInteger("count");
        Integer cityId = jsonObject.getInteger("cityId");
        String isSpellOrder = jsonObject.getString("isSpellOrder");
        String isUseIntegral = jsonObject.getString("isUseIntegral");
        Result<CarPriceResult> result = Result.success(null);
        CarPriceResult integralPrice = skuOrderService.getIntegralBySku(cityId, merchant.getUserId(), skuId, skuSalesInformationId, count, isSpellOrder, isUseIntegral);
        result.setData(integralPrice);
        return result;
    }

    @OperLog(operModul = "商户-普通商品下单", operDesc = "普通商品下单")
    @LoginCheck
    @RequestMapping(value = "/pay/skuOrder", method = {RequestMethod.POST})
    public Result<PayParam> paySkuOrder(@RequestBody SkuOrderAddByDirectReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            skuOrderAddReq.setIsByBalance("N");
            OrderResult orderResult = skuOrderService.addOrderByDirect(skuOrderAddReq);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("普通商品下单");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            logger.info("req===" + JSONObject.toJSONString(req));
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(req.getAmount());
                    payOrder.setAppletType(skuOrderAddReq.getAppletType());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(skuOrderAddReq.getAppletType());
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            environment + req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            } else {
                inquireOrderService.notifyRecharge(Integer.parseInt(orderAndPay.getOrderId()), System.currentTimeMillis() + "", new Date(), new HashMap<>());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-购物车下单", operDesc = "购物车下单")
    @LoginCheck
    @RequestMapping(value = "/pay/carOrder", method = {RequestMethod.POST})
    public Result<PayParam> payCarOrder(@RequestBody SkuOrderAddReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            skuOrderAddReq.setIsByBalance("N");
            OrderResult orderResult = skuOrderService.addOrderByCar(skuOrderAddReq);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("购物车下单");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(req.getAmount());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(skuOrderAddReq.getAppletType());
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            environment + req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            } else {
                inquireOrderService.notifyRecharge(Integer.parseInt(orderAndPay.getOrderId()), System.currentTimeMillis() + "", new Date(), new HashMap<>());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(111111, e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-普通商品余额下单", operDesc = "普通商品余额下单")
    @LoginCheck
    @RequestMapping(value = "/pay/skuOrderByBalance", method = {RequestMethod.POST})
    public Result<String> paySkuOrderByBalance(@RequestBody SkuOrderAddByDirectReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            skuOrderAddReq.setIsByBalance("Y");
            OrderResult orderResult = skuOrderService.addOrderByDirect(skuOrderAddReq);
            skuOrderService.payOrderByBalance(orderResult);
            result.setData("SUCCESS");
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-购物车余额下单", operDesc = "购物车余额下单")
    @LoginCheck
    @RequestMapping(value = "/pay/carOrderByBalance", method = {RequestMethod.POST})
    public Result<String> payCarOrderByBalance(@RequestBody SkuOrderAddReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            skuOrderAddReq.setIsByBalance("Y");
            OrderResult orderResult = skuOrderService.addOrderByCar(skuOrderAddReq);
            skuOrderService.payCarOrderByBalance(orderResult);
            result.setData("SUCCESS");
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(111111, e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-分期购定金下单", operDesc = "分期购定金下单")
    @LoginCheck
    @RequestMapping(value = "/pay/periodizationDepositOrder", method = {RequestMethod.POST})
    public Result<PayParam> payPeriodizationDepositOrder(@RequestBody PeriodizationDepositOrderReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            OrderResult orderResult = skuOrderService.addPeriodizationDepositOrder(skuOrderAddReq);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("分期购定金");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            logger.info("req===" + JSONObject.toJSONString(req));
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(req.getAmount());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(skuOrderAddReq.getAppletType());
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            environment + req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            } else {
                inquireOrderService.notifyRecharge(Integer.parseInt(orderAndPay.getOrderId()), System.currentTimeMillis() + "", new Date(), new HashMap<>());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }


    @OperLog(operModul = "商户-分期购定金下单", operDesc = "分期购定金下单")
    @LoginCheck
    @RequestMapping(value = "/pay/periodizationOrderReq", method = {RequestMethod.POST})
    public Result<PayParam> payPeriodizationDepositOrder(@RequestBody PeriodizationOrderReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            OrderResult orderResult = skuOrderService.addPeriodizationOrderReq(skuOrderAddReq);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("分期购下单");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            logger.info("req===" + JSONObject.toJSONString(req));
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(req.getAmount());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(skuOrderAddReq.getAppletType());
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            environment + req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            } else {
                inquireOrderService.notifyRecharge(Integer.parseInt(orderAndPay.getOrderId()), System.currentTimeMillis() + "", new Date(), new HashMap<>());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }


    @OperLog(operModul = "商户-先享后付提交订单", operDesc = "先享后付提交订单")
    @LoginCheck
    @RequestMapping(value = "/pay/enjoy", method = {RequestMethod.POST})
    public Result<String> payEnjoy(@RequestBody SkuOrderAddByDirectReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            String s = skuOrderService.addOrderByEnjoy(skuOrderAddReq);
            result.setData("SUCCESS");
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(111111, e.getMessage());
        }
        return result;
    }


    @OperLog(operModul = "商户-先享后付提交订单", operDesc = "先享后付提交订单")
    @LoginCheck
    @RequestMapping(value = "/pay/enjoyByCar", method = {RequestMethod.POST})
    public Result<OrderResult> payEnjoy(@RequestBody SkuOrderAddReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<OrderResult> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            OrderResult orderResult = skuOrderService.addOrderCarByEnjoy(skuOrderAddReq);
            result.setData(orderResult);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(111111, e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-先享后付下单", operDesc = "先享后付下单")
    @LoginCheck
    @RequestMapping(value = "/pay/enjoyOrder", method = {RequestMethod.POST})
    public Result<PayParam> payEnjoyOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        String date = jsonObject.getString("date");
        String openId = jsonObject.getString("openId");
        Integer appletType = jsonObject.getInteger("appletType");
        Result<PayParam> result = Result.success(null);
        try {
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setSubject("先享后付同意支付");
            req.setOutOrderId(environment + SkuOrderTypeEnum.ENJOY.getCode() + "-" + merchant.getUserId() + "-" + date + DateUtil.getDateTime(new Date(), "MMddHHmm"));
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.ENJOY);
            req.setOpenId(openId);
            req.setDate(date);
            PayParam orderAndPay = commonPayService.payOrderByEnjoy(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(orderAndPay.getAmount());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(appletType);
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            environment + req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            } else {
                inquireOrderService.notifyRecharge(Integer.parseInt(orderAndPay.getOrderId()), System.currentTimeMillis() + "", new Date(), new HashMap<>());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(111111, e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-继续下单", operDesc = "继续下单")
    @LoginCheck
    @RequestMapping(value = "/pay/continue", method = {RequestMethod.POST})
    public Result<PayParam> continuePay(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        Result<PayParam> result = Result.success(null);
        try {
            Integer skuOrderId = jsonObject.getInteger("skuOrderId");
            Integer merchantCityId = jsonObject.getInteger("merchantCityId");
            String openId = jsonObject.getString("openId");
            Integer cityId = jsonObject.getInteger("cityId");
            Integer appletType = jsonObject.getInteger("appletType");
            OrderResult orderResult = skuOrderService.continuePay(skuOrderId, merchant.getUserId(), merchantCityId, cityId, "N");
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("继续购买");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(openId);
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(req.getAmount());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(appletType);
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            environment + req.getOrderTypeEnum().getCode() + StringUtil.getRandomDigit(4) + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            } else {
                inquireOrderService.notifyRecharge(Integer.parseInt(orderAndPay.getOrderId()), System.currentTimeMillis() + "", new Date(), new HashMap<>());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-继续下单余额支付", operDesc = "继续下单余额支付")
    @LoginCheck
    @RequestMapping(value = "/pay/continueByBalance", method = {RequestMethod.POST})
    public Result<String> continuePayByBalance(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        Result<String> result = Result.success(null);
        try {
            Integer skuOrderId = jsonObject.getInteger("skuOrderId");
            Integer merchantCityId = jsonObject.getInteger("merchantCityId");
            String openId = jsonObject.getString("openId");
            Integer cityId = jsonObject.getInteger("cityId");
            Integer appletType = jsonObject.getInteger("appletType");
            OrderResult orderResult = skuOrderService.continuePay(skuOrderId, merchant.getUserId(), merchantCityId, cityId, "Y");
            inquireOrderService.payContinueByBalance(orderResult);
            result.setData("success");
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-物流付费", operDesc = "物流付费")
    @LoginCheck
    @RequestMapping(value = "/pay/skuLogistics", method = {RequestMethod.POST})
    public Result<PayParam> orderPay(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        try {
            Integer skuOrderDeliveryDemandId = jsonObject.getInteger("skuOrderDeliveryDemandId");
            String returnUrl = jsonObject.getString("returnUrl");
            String openId = jsonObject.getString("openId");
            Integer appletType = jsonObject.getInteger("appletType");
            OrderResult orderResult = skuOrderService.logisticsPay(merchant.getUserId(), skuOrderDeliveryDemandId);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("小宗物流支付");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setReturnUrl(returnUrl);
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.LOGISTICS);
            req.setOpenId(openId);
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(req.getAmount());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(appletType);
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-商品订单列表", operDesc = "商品订单列表")
    @RequestMapping(value = "/order/list", method = {RequestMethod.POST})
    public Result<SkuOrderCountResult> skuPlaceOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<SkuOrderCountResult> result = Result.success(null);
        if (merchant==null){
            return result;
        }
        String status = jsonObject.getString("status");
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        Integer pageSize = jsonObject.getInteger("pageSize");
        PagerInfo pagerInfo = new PagerInfo(pageSize, pageIndex);
        SkuOrderCountResult merchantOrderResult = skuOrderService.getMerchantOrderResult(status, merchant.getUserId(), pagerInfo);
        result.setData(merchantOrderResult);
        return result;
    }


    @OperLog(operModul = "商户-商品订单列表", operDesc = "商品所有订单列表")
    @LoginCheck
    @RequestMapping(value = "/order/all/list", method = {RequestMethod.POST})
    public Result<List<SkuOrderResult>> orderAllList(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<List<SkuOrderResult>> result = Result.success(null);
        List<SkuOrderResult> merchantOrderResultByNoSuccess = skuOrderService.getMerchantOrderResultByNoSuccess(merchant.getUserId());
        result.setData(merchantOrderResultByNoSuccess);
        return result;
    }


    @OperLog(operModul = "商户-商品订单列表", operDesc = "商品所有订单列表")
    @LoginCheck
    @RequestMapping(value = "/periodization/order/list", method = {RequestMethod.POST})
    public Result<List<SkuOrderResult>> periodizationOrderList(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<List<SkuOrderResult>> result = Result.success(null);
        List<SkuOrderResult> merchantOrderResultByNoSuccess = skuOrderService.getMerchantOrderResultByNoSuccess(merchant.getUserId());
        result.setData(merchantOrderResultByNoSuccess);
        return result;
    }


    @OperLog(operModul = "商户-商品订单详情", operDesc = "商品订单详情")
    @LoginCheck
    @RequestMapping(value = "/order/detail", method = {RequestMethod.POST})
    public Result<SkuOrderResult> skuOrderResultDetail(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<SkuOrderResult> result = Result.success(null);
        Integer skuOrderId = jsonObject.getInteger("skuOrderId");
        SkuOrderResult skuOrderResultDetail = null;
        try {
            skuOrderResultDetail = skuOrderService.getSkuOrderResultDetail(skuOrderId, merchant.getUserId());
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData(skuOrderResultDetail);
        return result;
    }

    @OperLog(operModul = "商户-确认收货", operDesc = "确认收货")
    @LoginCheck
    @RequestMapping(value = "/sku/confirm/order", method = {RequestMethod.POST})
    public Result<String> confirmOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer id = jsonObject.getInteger("skuOrderId");
        Result<String> result = Result.success(null);
        skuOrderService.confirmOrder(id, merchant.getUserId());
        return result;
    }

    @OperLog(operModul = "商户-取消订单", operDesc = "取消订单")
    @LoginCheck
    @RequestMapping(value = "/sku/cancel/order", method = {RequestMethod.POST})
    public Result<String> cancelOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer id = jsonObject.getInteger("skuOrderId");
        String applyRefundReason = jsonObject.getString("applyRefundReason");
        Result<String> result = Result.success(null);
        skuOrderService.cancelOrder(id, merchant.getUserId(), applyRefundReason);
        return result;
    }


    @OperLog(operModul = "商户-申请退款", operDesc = "申请退款")
    @LoginCheck
    @RequestMapping(value = "/applyRefund/order", method = {RequestMethod.POST})
    public Result<String> applyRefundOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer skuOrderDetailId = jsonObject.getInteger("skuOrderDetailId");
        String applyRefundReason = jsonObject.getString("applyRefundReason");
        Result<String> result = Result.success(null);
        skuOrderService.applyRefund(merchant.getUserId(), skuOrderDetailId, applyRefundReason);
        return result;
    }

    @OperLog(operModul = "商户-申请退款", operDesc = "申请退款")
    @LoginCheck
    @RequestMapping(value = "/cancel/applyRefund/order", method = {RequestMethod.POST})
    public Result<String> cancelApplyRefundOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer skuOrderDetailId = jsonObject.getInteger("skuOrderDetailId");
        Result<String> result = Result.success(null);
        skuOrderService.cancelApplyRefund(merchant.getUserId(), skuOrderDetailId);
        return result;
    }

    public String getCover(HttpURLConnection httpURLConnection, String scene, String page) throws Exception {
        Object accessToken = redisService.get("xcxAccessToken");
        String accessTokenStr = null;
        if (accessToken == null) {
            JSONObject accessToken1 = WeixinGzhAppletsUtil.getAccessToken();
            accessToken1.put("expires_time", DateUtil.addSeconds(new Date(), accessToken1.getInteger("expires_in")));
            redisService.set("xcxAccessToken", accessToken1);
            accessTokenStr = accessToken1.getString("access_token");
        } else {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(accessToken));
            if (jsonObject.getDate("expires_time").before(new Date())) {
                JSONObject accessToken2 = WeixinGzhAppletsUtil.getAccessToken();
                accessToken2.put("expires_time", DateUtil.addSeconds(new Date(), accessToken2.getInteger("expires_in")));
                redisService.set("xcxAccessToken", accessToken2);
                accessTokenStr = accessToken2.getString("access_token");
            } else {
                accessTokenStr = jsonObject.getString("access_token");
            }
        }
        //小程序统一消息推送

        URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessTokenStr);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");// 提交模式
        // 发送POST请求必须设置如下两行
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.put("scene", scene);
        paramJson.put("page", page);
        logger.info("sceneSize===" + scene.length());
        if (environment.equals("stg")) {
            paramJson.put("env_version", "trial");
        }
        logger.info("paramJson===" + paramJson + ",token==" + accessTokenStr);
        printWriter.write(paramJson.toString());
        // flush输出流的缓冲
        printWriter.flush();
        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
        try (InputStream is = httpURLConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            String s = new String(baos.toByteArray());
            if (s.length() < 300) {
                JSONObject jsonObject = JSONObject.parseObject(s);
                Integer errcode = jsonObject.getInteger("errcode");
                if (errcode == 40001) {
                    JSONObject accessToken1 = WeixinGzhAppletsUtil.getAccessToken();
                    accessToken1.put("expires_time", DateUtil.addSeconds(new Date(), accessToken1.getInteger("expires_in")));
                    redisService.set("xcxAccessToken", accessToken1);
                    HttpURLConnection httpURLConnection1 = null;
                    return getCover(httpURLConnection1, scene, page);
                } else {
                    throw new BusinessException(errcode, jsonObject.getString("errmsg"));
                }

            }
            return ("data:image/png;base64," + Base64.encode(baos.toByteArray()));
        }
    }


    @OperLog(operModul = "商户-线下订单分享图片", operDesc = "线下订单分享图片")
    @RequestMapping(value = "/pay/offline/cover", method = {RequestMethod.POST})
    public Result<Map<String, Object>> payOfflineCover(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Integer orderId = jsonObject.getInteger("orderId");
        HttpURLConnection httpURLConnection = null;
        Map<String, Object> map = new HashMap<>();
        try {
            String cover = getCover(httpURLConnection, "o=" + orderId, "pages/home/subPages/underline-confirm/index");
            map.put("code", cover);
            return Result.success(map);
        } catch (
                BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (
                Exception e) {
            e.printStackTrace();
            return Result.failed(ExceptionEnum.ERROR_9999.getCode(), e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

    }

    @OperLog(operModul = "商户-朋友代付普通商品下单", operDesc = "朋友代付普通商品下单")
    @LoginCheck
    @RequestMapping(value = "/pay/friend/skuOrder", method = {RequestMethod.POST})
    public Result<Map<String, Object>> payFriendSkuOrder(@RequestBody SkuOrderAddByDirectReq skuOrderAddReq, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        LoginUser merchant = getMerchant();
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        HttpURLConnection httpURLConnection = null;
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            skuOrderAddReq.setIsByBalance("N");
            OrderResult orderResult = skuOrderService.addOrderByDirect(skuOrderAddReq);

            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("普通商品下单");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.FRIENDS.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            logger.info("req===" + JSONObject.toJSONString(req));
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            String cover = getCover(httpURLConnection, "o=" + orderAndPay.getOutOrderId() + "&m=" + merchant.getUserId(), "pages/home/subPages/friend-pay/index");
            map.put("code", cover);
            map.put("price", orderResult.getPayPrice());
            map.put("skuName", orderResult.getSkuNames());
            map.put("outOrderId", orderAndPay.getOutOrderId());
            map.put("merchantId", merchant.getUserId());
            return Result.success(map);
        } catch (
                BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (
                Exception e) {
            e.printStackTrace();
            return Result.failed(ExceptionEnum.ERROR_9999.getCode(), e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

    }

    @OperLog(operModul = "商户-朋友代付购物车下单", operDesc = "朋友代付购物车下单")
    @LoginCheck
    @RequestMapping(value = "/pay/friend/carOrder", method = {RequestMethod.POST})
    public Result<Map<String, Object>> payFriendCarOrder(@RequestBody SkuOrderAddReq skuOrderAddReq, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        LoginUser merchant = getMerchant();
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        HttpURLConnection httpURLConnection = null;
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            skuOrderAddReq.setIsByBalance("N");
            OrderResult orderResult = skuOrderService.addOrderByCar(skuOrderAddReq);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("购物车下单");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.FRIENDS.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            String cover = getCover(httpURLConnection, "o=" + orderAndPay.getOutOrderId() + "&m=" + merchant.getUserId(), "pages/home/subPages/friend-pay/index");
            map.put("code", cover);
            map.put("price", orderResult.getPayPrice());
            map.put("skuName", orderResult.getSkuNames());
            map.put("outOrderId", orderAndPay.getOutOrderId());
            map.put("merchantId", merchant.getUserId());
            return Result.success(map);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (
                Exception e) {
            e.printStackTrace();
            return Result.failed(ExceptionEnum.ERROR_9999.getCode(), e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
    }

    @OperLog(operModul = "商户-朋友代付继续下单", operDesc = "朋友代付继续下单")
    @LoginCheck
    @RequestMapping(value = "/pay/friend/continue", method = {RequestMethod.POST})
    public Result<Map<String, Object>> continueFriendPay(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        LoginUser merchant = getMerchant();
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        HttpURLConnection httpURLConnection = null;
        try {
            Integer skuOrderId = jsonObject.getInteger("skuOrderId");
            Integer merchantCityId = jsonObject.getInteger("merchantCityId");
            Integer cityId = jsonObject.getInteger("cityId");
            String openId = jsonObject.getString("openId");
            OrderResult orderResult = skuOrderService.continuePay(skuOrderId, merchant.getUserId(), merchantCityId, cityId, "N");
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("继续购买");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.FRIENDS.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(openId);
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            String cover = getCover(httpURLConnection, "o=" + orderAndPay.getOutOrderId() + "&m=" + merchant.getUserId(), "pages/home/subPages/friend-pay/index");
            map.put("code", cover);
            map.put("price", orderResult.getPayPrice());
            map.put("skuName", orderResult.getSkuNames());
            map.put("outOrderId", orderAndPay.getOutOrderId());
            map.put("merchantId", merchant.getUserId());
            return Result.success(map);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(ExceptionEnum.ERROR_9999.getCode(), e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
    }


    @OperLog(operModul = "商户-朋友支付下单", operDesc = "朋友支付下单")
    @RequestMapping(value = "/friend/pay", method = {RequestMethod.POST})
    public Result<PayParam> friendPay(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<PayParam> result = Result.success(null);
        try {
            String openId = jsonObject.getString("openId");
            String outOrderId = jsonObject.getString("outOrderId");
            Integer merchantId = jsonObject.getInteger("merchantId");
            Integer appletType = jsonObject.getInteger("appletType");
            ValidateBusinessException.assertStringNotBlank(openId, ExceptionEnum.ERROR_1866);
            ValidateBusinessException.assertStringNotBlank(outOrderId, ExceptionEnum.ERROR_1867);
            ValidateBusinessException.assertNonNull(merchantId, ExceptionEnum.ERROR_1868);
            PayParam orderAndPay = commonPayService.findByOrderId(merchantId, outOrderId);
            if (orderAndPay.getAmount() > 0) {
                PayOrderResult payOrder = new PayOrderResult();
                payOrder.setMoney(orderAndPay.getAmount());
                payOrder.setReturnUrl(null);
                payOrder.setTitle(EnumPayMethod.FRIENDS.getName());
                payOrder.setAppletType(appletType);
                Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, IpUtils.getIp(request), openId,
                        webDomain + "/wechat/applet/notifyUrl",
                        environment + EnumPayMethod.FRIENDS.getCode() + "-" + orderAndPay.getOrderId());
                orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
            } else {
                inquireOrderService.notifyRecharge(Integer.parseInt(orderAndPay.getOrderId()), System.currentTimeMillis() + "", new Date(), new HashMap<>());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }


    @OperLog(operModul = "商户-朋友支付详情", operDesc = "朋友支付详情")
    @RequestMapping(value = "/friend/order/detail", method = {RequestMethod.POST})
    public Result<FriendOrderResult> friendOrderDetail(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<FriendOrderResult> result = Result.success(null);
        try {
            String outOrderId = jsonObject.getString("outOrderId");
            Integer merchantId = jsonObject.getInteger("merchantId");
            ValidateBusinessException.assertStringNotBlank(outOrderId, ExceptionEnum.ERROR_1867);
            ValidateBusinessException.assertNonNull(merchantId, ExceptionEnum.ERROR_1868);
            FriendOrderResult friendOrderResultByOrderId = commonPayService.findFriendOrderResultByOrderId(merchantId, outOrderId);
            result.setData(friendOrderResultByOrderId);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "delete/key", method = {RequestMethod.POST})
    public Result<String> delete(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<String> result = Result.success(null);
        String key = request.getParameter("key");
        redisService.del(key);
        return result;
    }

    @OperLog(operModul = "商户-是否能先享后付", operDesc = "是否能先享后付")
    @LoginCheck
    @RequestMapping(value = "/order/isEnjoy", method = {RequestMethod.POST})
    public Result<Boolean> orderIsEnjoy(@RequestBody SkuOrderAddByDirectReq req, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<Boolean> result = Result.success(null);
        req.setMerchantId(merchant.getUserId());
        Boolean enjoy = null;
        try {
            enjoy = skuOrderService.isEnjoy(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData(enjoy);
        return result;
    }


    @OperLog(operModul = "商户-是否能先享后付", operDesc = "是否能先享后付")
    @LoginCheck
    @RequestMapping(value = "/order/isEnjoyByCar", method = {RequestMethod.POST})
    public Result<Boolean> orderIsEnjoy(@RequestBody SkuOrderAddReq req, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<Boolean> result = Result.success(null);
        req.setMerchantId(merchant.getUserId());
        Boolean enjoy = null;
        try {
            enjoy = skuOrderService.isEnjoyByCar(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData(enjoy);
        return result;
    }

    @OperLog(operModul = "商户-先享后付订单列表", operDesc = "先享后付订单列表")
    @RequestMapping(value = "/enjoy/order/list", method = {RequestMethod.POST})
    public Result<EnjoySkuOrderResult> enjoyOrderList(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<EnjoySkuOrderResult> result = Result.success(null);
        if (merchant==null){
            return result;
        }
        String date = jsonObject.getString("date");
        Integer dailiMerchantId = jsonObject.getInteger("dailiMerchantId");
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        Integer pageSize = jsonObject.getInteger("pageSize");
        PagerInfo pagerInfo = new PagerInfo(pageSize, pageIndex);
        EnjoySkuOrderResult enjoySkuOrderResult = skuOrderService.getEnjoySkuOrderResult(date, merchant.getUserId(), pagerInfo, dailiMerchantId);
        result.setData(enjoySkuOrderResult);
        return result;
    }


    @OperLog(operModul = "商户-普通商品线下下单", operDesc = "普通商品线下下单")
    @LoginCheck
    @RequestMapping(value = "/pay/addOrderByOffline", method = {RequestMethod.POST})
    public Result<PayParam> addOrderByOffline(@RequestBody SkuOrderAddByDirectReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        skuOrderAddReq.setMerchantId(skuOrderAddReq.getMerchantId());
        skuOrderAddReq.setPlaceMerchantId(merchant.getUserId());
        try {
            OrderResult orderResult = skuOrderService.addOrderByOffline(skuOrderAddReq);
            PayParam payParam = new PayParam();
            payParam.setOrderId(orderResult.getId() + "");
            result.setData(payParam);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-购物车线下下单", operDesc = "购物车线下下单")
    @LoginCheck
    @RequestMapping(value = "/pay/addOrderCarByOffline", method = {RequestMethod.POST})
    public Result<PayParam> payCarOrderByOffline(@RequestBody SkuOrderAddReq skuOrderAddReq, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        try {
            skuOrderAddReq.setMerchantId(skuOrderAddReq.getMerchantId());
            skuOrderAddReq.setPlaceMerchantId(merchant.getUserId());
            OrderResult orderResult = skuOrderService.addOrderCarByOffline(skuOrderAddReq);
            PayParam payParam = new PayParam();
            payParam.setOrderId(orderResult.getId() + "");
            result.setData(payParam);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(111111, e.getMessage());
        }
        return result;
    }


    @OperLog(operModul = "商户-确认线下下单", operDesc = "确认线下下单")
    @RequestMapping(value = "/pay/confirmOrderByOffline", method = {RequestMethod.POST})
    public Result<String> confirmOrderByOffline(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<String> result = Result.success(null);
        Integer orderId = jsonObject.getInteger("orderId");
        String smsCode = jsonObject.getString("smsCode");
        String mobile = jsonObject.getString("mobile");
        try {
            skuOrderService.confirmOrder(orderId, mobile, smsCode);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("success");
        return result;
    }


    @OperLog(operModul = "商户-查看线下订单", operDesc = "查看线下订单")
    @RequestMapping(value = "/pay/getSkuTotalResult", method = {RequestMethod.POST})
    public Result<SkuTotalResult> getSkuTotalResult(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<SkuTotalResult> result = Result.success(null);
        Integer orderId = jsonObject.getInteger("orderId");
        try {
            SkuTotalResult skuTotalResult = skuOrderService.getSkuTotalResult(orderId);
            result.setData(skuTotalResult);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }


    @OperLog(operModul = "商户-分页查看分期购订单", operDesc = "分页查看分期购订单")
    @LoginCheck
    @RequestMapping(value = "/pay/getPeriodizationResult", method = {RequestMethod.POST})
    public Result<Page<SkuOrderResult>> getPeriodizationResult(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<Page<SkuOrderResult>> result = Result.success(null);
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        Integer pageSize = jsonObject.getInteger("pageSize");
        PagerInfo pagerInfo = new PagerInfo(pageSize, pageIndex);
        Page<SkuOrderResult> merchantOrderResultByPeriodization = skuOrderService.getMerchantOrderResultByPeriodization(getMerchant().getUserId(), pagerInfo);
        result.setData(merchantOrderResultByPeriodization);
        return result;
    }

    @OperLog(operModul = "商户-查看分期购订单详情", operDesc = "查看分期购订单详情")
    @LoginCheck
    @RequestMapping(value = "/pay/getPeriodizationDetail", method = {RequestMethod.POST})
    public Result<PeriodizationOrderDetailResult> getPeriodizationDetail(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<PeriodizationOrderDetailResult> result = Result.success(null);
        Integer orderId = jsonObject.getInteger("orderId");
        PeriodizationOrderDetailResult periodizationOrderDetailResult = skuOrderService.getPeriodizationOrderDetailResult(getMerchant().getUserId(), orderId);
        result.setData(periodizationOrderDetailResult);
        return result;
    }

    @OperLog(operModul = "商户-查看分期购订单详情", operDesc = "查看分期购订单详情")
    @LoginCheck
    @RequestMapping(value = "/order/getPeriodizationPrice", method = {RequestMethod.POST})
    public Result<Map<Object, Object>> getPeriodizationDetail(@RequestBody PeriodizationOrderReq req, HttpServletRequest request) throws BusinessException {
        Result<Map<Object, Object>> result = Result.success(null);
        Map<Object, Object> periodizationPrice = skuOrderService.getPeriodizationPrice(req);
        result.setData(periodizationPrice);
        return result;
    }

    @OperLog(operModul = "商户-朋友代付分期购商品下单", operDesc = "朋友代付分期购商品下单")
    @LoginCheck
    @RequestMapping(value = "/pay/friend/periodizationDepositOrder", method = {RequestMethod.POST})
    public Result<Map<String, Object>> payFriendPeriodizationDepositOrder(@RequestBody PeriodizationDepositOrderReq skuOrderAddReq, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        LoginUser merchant = getMerchant();
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        HttpURLConnection httpURLConnection = null;
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            OrderResult orderResult = skuOrderService.addPeriodizationDepositOrder(skuOrderAddReq);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("分期购定金支付");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.FRIENDS.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            logger.info("req===" + JSONObject.toJSONString(req));
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            String cover = getCover(httpURLConnection, "o=" + orderAndPay.getOutOrderId() + "&m=" + merchant.getUserId(), "pages/home/subPages/friend-pay/index");
            map.put("code", cover);
            map.put("price", orderResult.getPayPrice());
            map.put("skuName", orderResult.getSkuNames());
            map.put("outOrderId", orderAndPay.getOutOrderId());
            map.put("merchantId", merchant.getUserId());
            return Result.success(map);
        } catch (
                BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (
                Exception e) {
            e.printStackTrace();
            return Result.failed(ExceptionEnum.ERROR_9999.getCode(), e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

    }


    @OperLog(operModul = "商户-朋友代付分期购商品下单", operDesc = "朋友代付分期购商品下单")
    @LoginCheck
    @RequestMapping(value = "/pay/friend/periodizationOrder", method = {RequestMethod.POST})
    public Result<Map<String, Object>> addPeriodizationOrderReq(@RequestBody PeriodizationOrderReq skuOrderAddReq, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        LoginUser merchant = getMerchant();
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (!merchantResult.getBuyPermission().contains(SkuTypeEnum.SKU.getCode())) {
            return Result.failed(ExceptionEnum.ERROR_1862);
        }
        HttpURLConnection httpURLConnection = null;
        try {
            skuOrderAddReq.setMerchantId(merchant.getUserId());
            OrderResult orderResult = skuOrderService.addPeriodizationOrderReq(skuOrderAddReq);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("分期购分期支付");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.FRIENDS.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(skuOrderAddReq.getOpenId());
            logger.info("req===" + JSONObject.toJSONString(req));
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            String cover = getCover(httpURLConnection, "o=" + orderAndPay.getOutOrderId() + "&m=" + merchant.getUserId(), "pages/home/subPages/friend-pay/index");
            map.put("code", cover);
            map.put("price", orderResult.getPayPrice());
            map.put("skuName", orderResult.getSkuNames());
            map.put("outOrderId", orderAndPay.getOutOrderId());
            map.put("merchantId", merchant.getUserId());
            return Result.success(map);
        } catch (
                BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (
                Exception e) {
            e.printStackTrace();
            return Result.failed(ExceptionEnum.ERROR_9999.getCode(), e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

    }

    @OperLog(operModul = "商户-普通商品下单", operDesc = "普通商品下单")
    @LoginCheck
    @RequestMapping(value = "/pay/balanceOrder", method = {RequestMethod.POST})
    public Result<PayParam> payBalanceOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        Double amount = jsonObject.getDouble("amount");
        String openId = jsonObject.getString("openId");
        Integer appletType = jsonObject.getInteger("appletType");
        OrderBalanceResult orderBalanceResult = new OrderBalanceResult();
        orderBalanceResult.setBalanceMoney(amount);
        orderBalanceResult.setMerchantId(merchant.getUserId());
        orderBalanceResult.setCreateTime(new Date());
        try {
            OrderResult orderResult = orderBalanceService.addOrUpdate(orderBalanceResult);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("余额充值");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.getByCode(orderResult.getOrderType()));
            req.setOpenId(openId);
            logger.info("req===" + JSONObject.toJSONString(req));
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                PayOrderResult payOrder = new PayOrderResult();
                payOrder.setMoney(req.getAmount());
                payOrder.setAppletType(appletType);
                payOrder.setReturnUrl(req.getReturnUrl());
                payOrder.setTitle(req.getSubject());
                Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                        webDomain + "/wechat/applet/notifyUrl",
                        environment + req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
            } else {
                throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-查看账户余额明细列表", operDesc = "查看分期购订单详情")
    @LoginCheck
    @RequestMapping(value = "/order/balanceList", method = {RequestMethod.POST})
    public Result<Page<OrderBalanceResult>> getOrderBalanceList(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        Result<Page<OrderBalanceResult>> result = Result.success(null);
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        Integer pageSize = jsonObject.getInteger("pageSize");
        PagerInfo pagerInfo = new PagerInfo(pageSize, pageIndex);
        OrderBalanceQuery orderBalanceQuery = new OrderBalanceQuery();
        orderBalanceQuery.setStatus("success");
        orderBalanceQuery.setMerchantId(getMerchant().getUserId());
        Page<OrderBalanceResult> orderBalanceResultPage = orderBalanceService.getPager(orderBalanceQuery, pagerInfo);
        result.setData(orderBalanceResultPage);
        return result;
    }


}
